Importing Classes and Packages in Java
Course: Core Java Training
Topic: Importing Classes and Packages
Course Link: Core Java Training Course
Demo Link: Register for a Course Demo
Website: JustAcademy Official Website
1. Introduction to Importing Classes and Packages
Java provides a package system to organize related classes, interfaces, and other types into logical groups. When a program needs to use a class defined in another package, Java allows the programmer to import that class or refer to it using its fully qualified name.
The import keyword makes types from other packages available by their simple names within a source file. It improves readability and reduces the need to repeatedly write long package names.
For example, the ArrayList class belongs to the java.util package. By importing it, a programmer can write ArrayList instead of java.util.ArrayList.
2. Learning Objectives
After completing this topic, you will be able to:
- Understand the purpose of importing classes and packages.
- Use the
import keyword in Java programs.
- Import a single class from a package.
- Use wildcard imports to access types from a package.
- Understand fully qualified class names.
- Import and use user-defined classes.
- Understand static imports and their applications.
- Identify the difference between package declarations and import statements.
- Resolve common import-related compilation errors.
3. What Is an Import Statement in Java?
An import statement allows a Java source file to refer to accessible classes and interfaces from other packages by their simple names. Without an import statement, a class from another package can generally be referenced using its fully qualified name.
Syntax
import packageName.ClassName;
Here, import is the keyword, packageName identifies the package, and ClassName specifies the class to import.
Example
import java.util.Scanner;
public class Main {
public static void main(String[] args) {
Scanner scanner = new Scanner(System.in);
System.out.print("Enter your name: ");
String name = scanner.nextLine();
System.out.println("Welcome, " + name);
scanner.close();
}
}
Sample Output
Enter your name: Rahul
Welcome, Rahul
Explanation: The statement import java.util.Scanner; allows the program to use the Scanner class without writing its full package name every time.
4. Why Do We Import Classes and Packages?
Import statements help make Java programs more readable and easier to maintain.
4.1 Improved Readability
Importing a class allows developers to use its simple name rather than repeatedly writing the full package path.
4.2 Code Reusability
Developers can use existing Java library classes or public classes created in other packages instead of implementing the same functionality again.
4.3 Easier Maintenance
Import statements make dependencies visible near the beginning of a source file, helping developers understand which external types the program uses.
4.4 Access to Java Libraries
Java provides classes for collections, file handling, date and time operations, networking, database connectivity, and many other tasks. Imports help programmers use these library classes conveniently.
4.5 Use of User-Defined Classes
Import statements allow classes in one package to use accessible public classes defined in another package.
5. Types of Import Statements in Java
Java supports different forms of import declarations for classes, interfaces, and static members.
| Import Type |
Purpose |
Example |
| Single-Type Import |
Imports one specific class or interface. |
import java.util.ArrayList; |
| Wildcard Import |
Makes accessible types from a package available by simple name. |
import java.util.*; |
| Static Import |
Imports a specific accessible static member. |
import static java.lang.Math.PI; |
| Static Wildcard Import |
Makes accessible static members of a type available by simple name. |
import static java.lang.Math.*; |
6. Importing a Single Class
A single-type import allows a program to use one specific class or interface from another package. This approach clearly communicates which external type the program depends on.
Syntax
import packageName.ClassName;
Example: Importing ArrayList
import java.util.ArrayList;
public class Main {
public static void main(String[] args) {
ArrayList<String> courses = new ArrayList<>();
courses.add("Java");
courses.add("Python");
courses.add("SQL");
System.out.println(courses);
}
}
Output
[Java, Python, SQL]
Explanation: The program imports only the ArrayList class from java.util. It then creates a list and stores three course names.
7. Importing Multiple Classes
A Java program can import multiple classes by using separate import statements. Each import statement identifies one class or interface.
Example
import java.util.ArrayList;
import java.util.HashMap;
import java.util.Scanner;
public class Main {
public static void main(String[] args) {
ArrayList<String> names = new ArrayList<>();
HashMap<Integer, String> students = new HashMap<>();
names.add("Amit");
names.add("Priya");
students.put(101, "Amit");
students.put(102, "Priya");
System.out.println(names);
System.out.println(students);
}
}
Output
[Amit, Priya]
{101=Amit, 102=Priya}
Explanation: The program imports ArrayList, HashMap, and Scanner. The first two classes are used to store data in different collection structures. The Scanner import is unnecessary in this particular example because the program does not use it; removing unused imports keeps the code clean.
8. Importing All Types From a Package
Java supports wildcard imports using the asterisk (*). A wildcard import makes accessible types declared directly in the specified package available by their simple names.
Syntax
import packageName.*;
Example
import java.util.*;
public class Main {
public static void main(String[] args) {
ArrayList<String> names = new ArrayList<>();
HashSet<Integer> numbers = new HashSet<>();
names.add("Rahul");
names.add("Neha");
numbers.add(10);
numbers.add(20);
numbers.add(10);
System.out.println(names);
System.out.println(numbers);
}
}
Sample Output
[Rahul, Neha]
[10, 20]
Explanation: The wildcard import makes both ArrayList and HashSet available without separate import statements. The set stores unique values, so the repeated value 10 appears only once.
Important: A wildcard import does not import subpackages. For example, import java.util.*; does not import classes from java.util.concurrent. It also does not import static members; static imports require the import static syntax.
9. Using Fully Qualified Class Names
A fully qualified class name includes the complete package name followed by the class name. Java allows developers to use this name instead of writing an import statement.
Example
public class Main {
public static void main(String[] args) {
java.util.ArrayList<String> languages =
new java.util.ArrayList<>();
languages.add("Java");
languages.add("JavaScript");
languages.add("Python");
System.out.println(languages);
}
}
Output
[Java, JavaScript, Python]
Explanation: The program uses java.util.ArrayList directly, so an import statement is not required.
When Should You Use Fully Qualified Names?
- When two packages contain classes with the same simple name.
- When a class is used only once and an import would not improve clarity.
- When you want to make the origin of a particular type explicit.
10. Importing Classes From User-Defined Packages
Developers can create their own packages and import public classes from them into other source files.
Step 1: Create a Package Class
Create a directory named calculator and add a file named Calculator.java.
package calculator;
public class Calculator {
public int add(int a, int b) {
return a + b;
}
public int multiply(int a, int b) {
return a * b;
}
}
Step 2: Import the Class
Create a Main.java file outside the calculator package directory.
import calculator.Calculator;
public class Main {
public static void main(String[] args) {
Calculator calculator = new Calculator();
System.out.println("Addition: " + calculator.add(12, 8));
System.out.println("Multiplication: " + calculator.multiply(12, 8));
}
}
Output
Addition: 20
Multiplication: 96
Explanation: The Calculator class belongs to the user-defined calculator package. The Main class imports it and calls its public methods.
11. Common Built-in Packages Used in Java
Java includes many standard packages that provide reusable functionality for application development.
| Package |
Purpose |
Common Classes |
java.lang |
Fundamental language functionality. |
String, Math, System, Object |
java.util |
Collections and utility classes. |
ArrayList, HashMap, Scanner |
java.io |
Traditional input and output operations. |
File, FileReader, BufferedReader |
java.time |
Date and time operations. |
LocalDate, LocalTime, LocalDateTime |
java.net |
Networking operations. |
URI, URL, Socket |
java.sql |
Database access through JDBC. |
Connection, PreparedStatement, ResultSet |
Example: Importing Date and Time Classes
import java.time.LocalDate;
import java.time.LocalTime;
public class Main {
public static void main(String[] args) {
LocalDate today = LocalDate.now();
LocalTime currentTime = LocalTime.now();
System.out.println("Date: " + today);
System.out.println("Time: " + currentTime);
}
}
Explanation: The program imports LocalDate and LocalTime from java.time to work with dates and times.
12. The java.lang Package and Automatic Imports
The java.lang package contains fundamental classes used by almost every Java program. Java automatically makes its public types available by their simple names, so an explicit import is not normally required.
Example
public class Main {
public static void main(String[] args) {
String message = "Learning Java";
double result = Math.sqrt(81);
System.out.println(message);
System.out.println(result);
System.out.println(Integer.MAX_VALUE);
}
}
Output
Learning Java
9.0
2147483647
The classes String, Math, and Integer belong to java.lang, so no explicit import is needed.
13. Static Imports in Java
A static import allows a program to use accessible static fields or methods without qualifying them with the declaring class name.
Syntax for Importing One Static Member
import static packageName.ClassName.memberName;
Example
import static java.lang.Math.PI;
import static java.lang.Math.sqrt;
public class Main {
public static void main(String[] args) {
double radius = 4;
double area = PI * radius * radius;
System.out.println("Area: " + area);
System.out.println("Square root: " + sqrt(64));
}
}
Output
Area: 50.26548245743669
Square root: 8.0
Explanation: The program imports the static constant PI and the static method sqrt() from Math. They can be used directly without writing Math.PI or Math.sqrt().
Wildcard Static Import
import static java.lang.Math.*;
This statement makes accessible static members of Math available by simple name. Use static imports carefully because excessive use can make the origin of a method or constant less obvious.
14. Importing Classes With the Same Name
Sometimes two packages contain classes with the same simple name. Importing both classes by their simple names in the same source file causes a naming conflict.
Example
The Java API contains both java.util.Date and java.sql.Date.
public class Main {
public static void main(String[] args) {
java.util.Date currentDate = new java.util.Date();
java.sql.Date sqlDate =
java.sql.Date.valueOf("2026-10-23");
System.out.println(currentDate);
System.out.println(sqlDate);
}
}
Explanation: The program uses fully qualified names to distinguish between the two classes. This avoids a conflict between their shared simple name, Date.
15. Difference Between Importing a Class and Importing a Package
Java's wildcard import syntax refers to accessible types in a package; it does not load or copy an entire package into the program.
| Feature |
Single-Class Import |
Wildcard Package Import |
| Syntax |
import java.util.ArrayList; |
import java.util.*; |
| Scope |
One named type. |
Accessible types directly in the named package. |
| Readability |
Clearly identifies the imported type. |
Can reduce the number of import statements. |
| Subpackages |
Does not automatically import subpackages. |
Does not automatically import subpackages. |
| Runtime behavior |
Does not copy or download the class. |
Does not copy or download the package. |
16. Rules for Import Statements
- Import statements appear after the package declaration, if present, and before top-level type declarations in a conventional Java source file.
- Imports are optional when a class is referenced by its fully qualified name.
- Classes and interfaces in
java.lang are automatically available by simple name.
- A wildcard import does not import subpackages.
- A wildcard package import does not import static members.
- Import declarations apply only to the source file in which they appear.
- Importing a class does not make its private members accessible.
- Importing a class does not bypass Java access modifiers or module-access restrictions.
- Two different types with the same simple name cannot both be imported by conflicting single-type imports in the same compilation unit.
- Unused imports should be removed to keep code clean and avoid unnecessary clutter.
17. Common Errors When Importing Classes and Packages
17.1 Missing Import Statement
Problem: The compiler cannot resolve a class name because the required type is neither imported nor referenced by its fully qualified name.
Solution: Add the appropriate import statement or use the fully qualified name.
17.2 Incorrect Package Name
Problem: The import statement uses the wrong package name or class name.
Solution: Verify the package declaration, spelling, capitalization, and class name.
17.3 Importing a Class That Is Not Accessible
Problem: A class is not declared public or is otherwise inaccessible from the current package or module.
Solution: Check class visibility, package membership, and module configuration.
17.4 Importing Two Classes With the Same Simple Name
Problem: Two single-type imports refer to different classes with the same simple name.
Solution: Remove the conflicting imports and use fully qualified names where needed.
17.5 Assuming Wildcard Imports Include Subpackages
Problem: A programmer expects import java.util.*; to import classes from java.util.concurrent.
Solution: Import the required types from the subpackage separately.
17.6 Incorrect Classpath
Problem: The compiler or Java launcher cannot locate a user-defined class.
Solution: Check the source directory, compiled output directory, and classpath configuration.
18. Best Practices for Importing Classes and Packages
- Prefer explicit single-type imports when they make dependencies easier to understand.
- Use wildcard imports only when they improve readability and comply with the project's coding standards.
- Use fully qualified names to resolve naming conflicts.
- Organize classes into meaningful packages.
- Remove unused imports from source files.
- Use static imports sparingly and only when they improve clarity.
- Do not assume imports provide access to private or package-private members.
- Keep import declarations consistent across the project.
- Use IDE features to organize imports and detect unresolved references.
- Check the classpath when working with user-defined packages or external libraries.
19. Practical Project: Student Course Management
Create a simple project that stores student information using a user-defined package and Java's built-in collection classes.
File 1: Student.java
Create the file inside a directory named student.
package student;
public class Student {
private String name;
private int rollNumber;
public Student(String name, int rollNumber) {
this.name = name;
this.rollNumber = rollNumber;
}
public void displayDetails() {
System.out.println("Student Name: " + name);
System.out.println("Roll Number: " + rollNumber);
}
}
File 2: Main.java
Create the main class in the source root.
import student.Student;
import java.util.ArrayList;
public class Main {
public static void main(String[] args) {
ArrayList<Student> students = new ArrayList<>();
students.add(new Student("Aarav", 101));
students.add(new Student("Diya", 102));
for (Student student : students) {
student.displayDetails();
System.out.println();
}
}
}
Output
Student Name: Aarav
Roll Number: 101
Student Name: Diya
Roll Number: 102
Project Explanation
- The
Student class belongs to the user-defined student package.
- The
import student.Student; statement makes the Student class available by its simple name.
- The
import java.util.ArrayList; statement imports a built-in collection class.
- The
ArrayList stores multiple Student objects.
- The loop displays the details of each student.
20. Practice Exercises
Exercise 1: Import Scanner
Write a program that imports Scanner, accepts two integers from the user, and displays their sum.
Exercise 2: Import ArrayList
Create an ArrayList of five programming languages and display each language using a loop.
Exercise 3: Import a User-Defined Class
Create a package named employee with an Employee class. Import it into a separate main program and display employee details.
Exercise 4: Use Fully Qualified Names
Write a program that uses java.util.Date and java.sql.Date without importing either class.
Exercise 5: Practice Static Imports
Import Math.PI and Math.pow() and use them to calculate the area of a circle.
Exercise 6: Explore Wildcard Imports
Use import java.util.*; to create an ArrayList, HashSet, and HashMap in the same program.
21. Interview Questions and Answers
Q1. What is an import statement in Java?
Answer: An import statement allows accessible classes and interfaces from another package to be referred to by their simple names within a source file.
Q2. Which keyword is used to import classes?
Answer: The import keyword is used to import classes and interfaces.
Q3. What is a single-type import?
Answer: A single-type import imports one specific class or interface, such as import java.util.Scanner;.
Q4. What is a wildcard import?
Answer: A wildcard import uses * to make accessible types directly within a package available by their simple names.
Q5. Does importing a package import its subpackages?
Answer: No. Each subpackage is separate and must be referenced or imported independently.
Q6. What is a fully qualified class name?
Answer: It is the complete class name, including its package name, such as java.util.ArrayList.
Q7. Is importing java.lang necessary?
Answer: No. Java automatically makes public types from java.lang available by their simple names.
Q8. What is a static import?
Answer: A static import allows accessible static fields or methods to be used without qualifying them with their declaring class name.
Q9. Can two classes with the same simple name be imported together?
Answer: Different classes with the same simple name cannot both be imported through conflicting single-type imports in the same compilation unit. Fully qualified names can be used to distinguish them.
Q10. Do import statements load classes into memory immediately?
Answer: No. Import statements are compile-time naming conveniences. They do not themselves load classes into memory or copy classes into the program.
Q11. Can an import statement access private members of a class?
Answer: No. Importing a class does not change the visibility of its members or bypass access-control rules.
Q12. What is the difference between import and static import?
Answer: A normal import makes a class or interface available by its simple name. A static import makes specified static members available by their simple names.
22. Quick Revision Checklist
- Understand the purpose of import statements.
- Know how to import a single class.
- Understand wildcard imports and their limitations.
- Use fully qualified class names when required.
- Know how to import user-defined classes.
- Understand automatic access to
java.lang types.
- Learn the syntax and purpose of static imports.
- Recognize naming conflicts between classes.
- Remember that imports do not bypass access modifiers.
- Practice compiling and running programs that use multiple packages.
23. Conclusion
Importing classes and packages is an essential Java skill that allows developers to reuse existing functionality and write cleaner, more readable code. By learning single-type imports, wildcard imports, fully qualified names, and static imports, you can work effectively with Java's built-in libraries and your own user-defined packages.
Practice the examples and exercises in this lesson to strengthen your understanding of package organization, import syntax, and Java compilation.
Continue Learning Core Java with JustAcademy
Explore the Core Java Training Course to learn more about Java fundamentals, object-oriented programming, packages, classes, and other essential programming concepts.
Register for a Course Demo to learn more about the available training options.
Visit the JustAcademy Official Website for additional course information and learning resources.